<template>
  <div class="admin-panel">
    <!-- 头部导航 -->
    <header class="header">
      <div class="container">
        <div class="logo">
          <router-link to="/" class="logo-link">
            <h1>伟邦人才信息网 - 信息统计</h1>
          </router-link>
        </div>
        <nav class="nav">
          <router-link to="/" class="nav-item">首页</router-link>
          <router-link to="/user" class="nav-item">个人中心</router-link>
          <router-link to="/admin" class="nav-item active">管理后台</router-link>
          <el-button @click="logout" type="text">退出</el-button>
        </nav>
      </div>
    </header>

    <!-- 主要内容 -->
    <div class="main-content">
      <div class="container">
        <!-- 统计概览 -->
        <div class="stats-overview">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Briefcase /></el-icon>
            </div>
            <div class="stat-content">
              <h3>岗位总数</h3>
              <p class="stat-number">{{ totalJobs }}</p>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <h3>用户总数</h3>
              <p class="stat-number">{{ totalUsers }}</p>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-content">
              <h3>客户登记</h3>
              <p class="stat-number">{{ totalCustomers }}</p>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <h3>今日新增</h3>
              <p class="stat-number">{{ todayNewCount }}</p>
            </div>
          </div>
        </div>

        <!-- 标签页 -->
        <el-tabs v-model="activeTab" @tab-change="tabChange" class="admin-tabs">
          <el-tab-pane label="岗位管理" name="jobs">
            <div class="tab-content">
              <div class="content-header">
                <h3>岗位列表</h3>
                <el-button type="primary" @click="showAddJobDialog">
                  <el-icon><Plus /></el-icon>
                  添加岗位
                </el-button>
              </div>
              
              <el-table :data="jobsList" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="positionId" label="ID" width="80" />
                <el-table-column prop="title" label="岗位名称" width="200" />
                <el-table-column prop="company" label="公司" width="150" />
                <el-table-column prop="location" label="地点" width="100" />
                <el-table-column prop="salary" label="薪资" width="100" />
                <el-table-column prop="createTime" label="发布时间" width="120" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
                      {{ scope.row.status === 'active' ? '上线' : '已下线' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template #default="scope">
                    <el-button size="small" @click="editJob(scope.row)">编辑</el-button>
                    <el-button size="small" type="success" @click="toggleJobStatus(scope.row)">
                      {{ scope.row.status === 'active' ? '下线' : '上线' }}
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteJob(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 批量操作按钮 -->
              <div class="batch-actions" v-if="selectedJobs.length > 0">
                <el-button type="danger" @click="batchDeleteJobs">
                  <el-icon><Delete /></el-icon>
                  批量删除 ({{ selectedJobs.length }})
                </el-button>
              </div>
              <el-pagination
                v-if="jobsPagination.total > 0"
                @size-change="handleJobsSizeChange"
                @current-change="handleJobsPageChange"
                :current-page="jobsPagination.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="jobsPagination.pageSize"
                layout="total, sizes, prev, pager, next"
                :total="jobsPagination.total"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="用户管理" name="users">
            <div class="tab-content">
              <div class="content-header">
                <h3>用户列表</h3>
                <!--<el-button type="primary" @click="showAddUserDialog">-->
                  <!--<el-icon><Plus /></el-icon>-->
                  <!--添加用户-->
                <!--</el-button>-->
              </div>
              
              <el-table :data="usersList" style="width: 100%">
                <el-table-column prop="userId" label="用户编号" width="80" />
                <el-table-column prop="userName" label="用户名" width="220" />
                <el-table-column prop="nickName" label="昵称" width="150" />
                <el-table-column prop="role" label="角色" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
                      {{ scope.row.role === 'admin' ? '管理员' : '业务员' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="phonenumber" label="手机号" width="" />
                <!--<el-table-column prop="wechat" label="微信号" width="120" />-->
                <!--<el-table-column prop="email" label="邮箱" width="180" />-->
                <!--<el-table-column label="操作" width="150">-->
                  <!--<template #default="scope">-->
                    <!--<el-button size="small" @click="editUser(scope.row)">编辑</el-button>-->
                    <!--<el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>-->
                  <!--</template>-->
                <!--</el-table-column>-->
              </el-table>
              <el-pagination
                v-if="usersPagination.total > 0"
                @size-change="handleUsersSizeChange"
                @current-change="handleUsersPageChange"
                :current-page="usersPagination.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="usersPagination.pageSize"
                layout="total, sizes, prev, pager, next"
                :total="usersPagination.total"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="客户管理" name="customers">
            <div class="tab-content">
              <div class="content-header">
                <h3>客户登记列表</h3>
                <!--<el-button type="primary" @click="exportAllCustomers">-->
                  <!--<el-icon><Download /></el-icon>-->
                  <!--导出所有客户-->
                <!--</el-button>-->
              </div>
              
              <el-table :data="customersList" style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="customerName" label="客户姓名" width="120" />
                <el-table-column prop="phone" label="手机号" width="130" />
                <el-table-column prop="wechat" label="微信号" width="120" />
                <el-table-column prop="email" label="邮箱" width="180" />
                <el-table-column prop="experience" label="工作经验" width="100" />
                <el-table-column prop="expectedSalary" label="期望薪资" width="100" />
                <el-table-column prop="shareUserName" label="分享者" width="100" />
                <el-table-column prop="registerTime" label="登记时间" width="160" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ getStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template #default="scope">
                    <el-button size="small" @click="viewCustomer(scope.row)">查看</el-button>
                    <el-button size="small" type="success" @click="updateCustomerStatus(scope.row, 'contacted')">
                      已联系
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                v-if="customersPagination.total > 0"
                @size-change="handleCustomersSizeChange"
                @current-change="handleCustomersPageChange"
                :current-page="customersPagination.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="customersPagination.pageSize"
                layout="total, sizes, prev, pager, next"
                :total="customersPagination.total"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="数据统计" name="statistics">
            <div class="tab-content">
              <div class="stats-grid">
                <div class="chart-card">
                  <h4>分享统计</h4>
                  <div class="chart-container">
                    <v-chart 
                      :option="shareChartOption" 
                      :style="{ height: '300px' }"
                      autoresize
                    />
                  </div>
                </div>
                
                <div class="chart-card">
                  <h4>客户转化</h4>
                  <div class="chart-container">
                    <v-chart 
                      :option="customerChartOption" 
                      :style="{ height: '300px' }"
                      autoresize
                    />
                  </div>
                </div>
                
                <div class="chart-card">
                  <h4>业务员排行</h4>
                  <div class="ranking-list">
                    <div v-for="(user, index) in topUsers" :key="user.id" class="ranking-item">
                      <span class="ranking-number">{{ index + 1 }}</span>
                      <span class="ranking-name">{{ user.salesmanName }}</span>
                      <span class="ranking-count">{{ user.shareCount }}个客户</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

        <el-tab-pane label="网站配置" name="index">
            <div class="tab-content">
                <div class="content-header">
                    <h3>网站配置</h3>
                    <el-button type="primary" @click="showAddIndexDialog">
                        <el-icon><Plus /></el-icon>
                        添加配置
                    </el-button>
                </div>

                <el-table :data="indexsList" style="width: 100%" @selection-change="handleSelectionIndex">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="id" label="ID" width="80" />
                    <!--<el-table-column prop="firstUrl" label="首页图片" width="200" />-->
                    <!--<el-table-column prop="bannerUrl" label="banner图片" width="150" />-->
                    <!--<el-table-column prop="searchUrl" label="搜索图片" width="100" />-->
                    <el-table-column prop="wwwName" label="网站名称" width="100" />
                    <el-table-column prop="status" label="状态" width="100">
                        <template #default="scope">
                            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
                                {{ scope.row.status === 'active' ? '上线' : '已下线' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="scope">
                            <el-button size="small" @click="editIndex(scope.row)">编辑</el-button>
                            <el-button size="small" type="success" @click="toggleIndexStatus(scope.row)">
                                {{ scope.row.status === 'active' ? '下线' : '上线' }}
                            </el-button>
                            <el-button size="small" type="danger" @click="deleteIndex(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 批量操作按钮 -->
                <div class="batch-actions" v-if="selectedIndexs.length > 0">
                    <el-button type="danger" @click="batchDeleteIndexs">
                        <el-icon><Delete /></el-icon>
                        批量删除 ({{ selectedIndexs.length }})
                    </el-button>
                </div>
                <el-pagination
                        v-if="indexsPagination.total > 0"
                        @size-change="handleIndexsSizeChange"
                        @current-change="handleIndexsPageChange"
                        :current-page="indexsPagination.pageNum"
                        :page-sizes="[10, 20, 50, 100]"
                        :page-size="indexsPagination.pageSize"
                        layout="total, sizes, prev, pager, next"
                        :total="indexsPagination.total"
                />
            </div>
        </el-tab-pane>

        </el-tabs>
      </div>
    </div>

    <!-- 添加网站对话框 -->
    <el-dialog :close-on-click-modal="false" v-model="indexDialogVisible" :title="isEditIndex ? '编辑网站' : '添加网站'" width="600px">
      <el-form :model="indexForm" :rules="indexRules" ref="indexFormRef" label-width="100px">
        <el-form-item label="网站名称" prop="wwwName">
          <el-input v-model="indexForm.wwwName" />
        </el-form-item>
        <el-form-item label="首页图片" prop="firstUrl">
          <FileUpload 
            v-model="indexForm.firstUrl"
            type="image" 
            :max-count="1"
            @change="handleImagesFirst"
          />
        </el-form-item>

      <el-form-item label="banner图片" prop="bannerUrl">
          <FileUpload
                  v-model="indexForm.bannerUrl"
                  type="image"
                  :max-count="5"
                  @change="handleImagesBanner"
          />
      </el-form-item>
      <el-form-item label="搜索图片" prop="searchUrl">
          <FileUpload
                  v-model="indexForm.searchUrl"
                  type="image"
                  :max-count="1"
                  @change="handleImagesSearch"
          />
      </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="indexDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveIndex">保存</el-button>
      </template>
    </el-dialog>

      <!-- 添加岗位对话框 -->
      <el-dialog :close-on-click-modal="false" v-model="jobDialogVisible" :title="isEditJob ? '编辑岗位' : '添加岗位'" width="600px">
          <el-form :model="jobForm" :rules="jobRules" ref="jobFormRef" label-width="100px">
              <el-form-item label="岗位名称" prop="title">
                  <el-input v-model="jobForm.title" />
              </el-form-item>
              <el-form-item label="公司名称" prop="company">
                  <el-input v-model="jobForm.company" />
              </el-form-item>
              <el-form-item label="工作地点" prop="location">
                  <el-input v-model="jobForm.location" />
              </el-form-item>
              <el-form-item label="薪资范围" prop="salary">
                  <el-input v-model="jobForm.salary" />
              </el-form-item>
              <el-form-item label="工作经验" prop="experience">
                  <el-input v-model="jobForm.experience" />
              </el-form-item>
              <el-form-item label="任职要求" prop="requirements">
                  <div class="requirement-list">
                      <div v-for="(requirement, index) in jobForm.requirements" :key="index" class="requirement-item">
                          <el-input
                                  v-model="jobForm.requirements[index]"
                                  placeholder="请输入任职要求"
                                  class="requirement-input"
                          />
                          <el-button
                                  type="danger"
                                  size="small"
                                  @click="removeRequirement(index)"
                                  class="remove-btn"
                          >
                              <el-icon><Delete /></el-icon>
                          </el-button>
                      </div>
                      <el-button
                              type="primary"
                              size="small"
                              @click="addRequirement"
                              class="add-btn"
                      >
                          <el-icon><Plus /></el-icon>
                          添加要求
                      </el-button>
                  </div>
              </el-form-item>

              <el-form-item label="福利待遇" prop="benefits">
                  <div class="requirement-list">
                      <div v-for="(benefit, index) in jobForm.benefits" :key="index" class="requirement-item">
                          <el-input
                                  v-model="jobForm.benefits[index]"
                                  placeholder="请输入福利待遇"
                                  class="requirement-input"
                          />
                          <el-button
                                  type="danger"
                                  size="small"
                                  @click="removeBenefit(index)"
                                  class="remove-btn"
                          >
                              <el-icon><Delete /></el-icon>
                          </el-button>
                      </div>
                      <el-button
                              type="primary"
                              size="small"
                              @click="addBenefit"
                              class="add-btn"
                      >
                          <el-icon><Plus /></el-icon>
                          添加福利
                      </el-button>
                  </div>
              </el-form-item>

              <!--<el-form-item label="学历要求" prop="education">-->
              <!--<el-input v-model="jobForm.education" />-->
              <!--</el-form-item>-->
              <el-form-item label="岗位描述" prop="description">
                  <el-input v-model="jobForm.description" type="textarea" :rows="3" />
              </el-form-item>

              <el-form-item label="岗位图片" prop="images">
                  <FileUpload
                          v-model="jobForm.images"
                          type="image"
                          :max-count="5"
                          @change="handleImagesChange"
                  />
              </el-form-item>

              <el-form-item label="岗位视频" prop="videos">
                  <FileUpload
                          v-model="jobForm.videos"
                          type="video"
                          :max-count="3"
                          @change="handleVideosChange"
                  />
              </el-form-item>

              <el-form-item label="相关文件" prop="files">
                  <FileUpload
                          v-model="jobForm.files"
                          type="file"
                          :max-count="5"
                          @change="handleFilesChange"
                  />
              </el-form-item>
          </el-form>
          <template #footer>
              <el-button @click="jobDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveJob">保存</el-button>
          </template>
      </el-dialog>

    <!-- 添加用户对话框 -->
    <el-dialog  :close-on-click-modal="false" v-model="userDialogVisible" :title="isEditUser ? '编辑用户' : '添加用户'" width="500px">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" style="width: 100%">
            <el-option label="业务员" value="sales" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <!--<el-form-item label="微信号" prop="wechat">-->
          <!--<el-input v-model="userForm.wechat" />-->
        <!--</el-form-item>-->
        <!--<el-form-item label="邮箱" prop="email">-->
          <!--<el-input v-model="userForm.email" />-->
        <!--</el-form-item>-->
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart } from 'echarts/charts'
import { deepClone } from '@/utils/index'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'

import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList,todayNewAdditions, getPositionList, positionAdd, positionUpdate,positionUpdateStatus, positionDel,
  userPost,userPut,userGet, customersAdd, getCusomer, cusomerList,cusomerUpdate, cusomerListMy,
  customerConversion,shareStatistic,salesmanRanking, uploadFile, batchDeletePositions,
  getWwwinfoList,wwwinfoAdd,wwwinfoUpdate,wwwinfoUpdateStatus,wwwinfoDel,getWwwinfoDetail,batchDeleteWwwinfo
} from "@/api/system"
import { FileUpload } from '@/components'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const router = useRouter()
const userStore = useUserStore()

const activeTab = ref('jobs')
const jobDialogVisible = ref(false)
const indexDialogVisible = ref(false)
const userDialogVisible = ref(false)
const isEditJob = ref(false)
const isEditUser = ref(false)
const isEditIndex = ref(false)

const jobFormRef = ref()
const indexFormRef = ref()
const userFormRef = ref()

// 选中的岗位
const selectedJobs = ref([])

// 选中的网站
const selectedIndexs = ref([])


// 表单数据
const jobForm = ref({
  title: '',
  company: '',
  location: '',
  salary: '',
  experience: '',
  requirements:[],
  benefits: [],
  education: '',
  description: '',
  images: [],
  videos: [],
  files: []
})

// 表单数据
const indexForm = ref({
  "bannerUrl": [],
  "bannerUrlList": [],
  "createBy": "",
  "createTime": "",
  "firstUrl": [],
  "params": {},
  "remark": "",
  "searchUrl": [],
  "status": "",
  "updateBy": "",
  "updateTime": "",
  "wwwName": ""
})

const userForm = ref({
  username: '',
  name: '',
  role: '',
  phone: '',
  wechat: '',
  email: ''
})

// 表单验证规则
const jobRules = {
  title: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
  company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  location: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
  salary: [{ required: true, message: '请输入薪资范围', trigger: 'blur' }],
  requirements: [
    { 
      required: true, 
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少添加一条任职要求'))
        } else if (value.some(item => !item || item.trim() === '')) {
          callback(new Error('任职要求不能为空'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

const indexRules = {
  wwwName: [{ required: true, message: '请输入网站名称', trigger: 'blur' }],
}


const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
}

// 统计数据
const totalJobs = computed(() => jobsPagination.value.total)
const totalUsers = computed(() => usersPagination.value.total)
const totalCustomers = computed(() => customersPagination.value.total)
const todayNewCount = ref(0)

// 列表数据
const jobsList = ref([])
const usersList = ref([])
const customersList = ref([])
const indexsList = ref([])

// 分页参数
const indexsPagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})
// 分页参数
const jobsPagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const usersPagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const customersPagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 图表数据
const shareChartOption = ref({
  title: {
    text: '近一周分享统计',
    left: 'center',
    textStyle: {
      fontSize: 16,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    name: '分享次数'
  },
  series: [
    {
      name: '分享次数',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#667eea'
      },
      barWidth: '60%'
    }
  ]
})

const customerChartOption = ref({
  title: {
    text: '近一周客户转化',
    left: 'center',
    textStyle: {
      fontSize: 16,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    name: '客户数量'
  },
  series: [
    {
      name: '客户数量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#764ba2'
      },
      barWidth: '60%'
    }
  ]
})

const getIndexListAll = async () => {
  try {
    const userInfo = await getWwwinfoList({
      pageNum: indexsPagination.value.pageNum,
      pageSize: indexsPagination.value.pageSize
    })
    indexsList.value = userInfo.rows || []
    indexsPagination.value.total = userInfo.total || 0
  } catch (error) {
    console.error('获取网站列表失败:', error)
    ElMessage.error('获取网站列表失败')
  }
}

const getJobListAll = async () => {
  try {
    const userInfo = await getPositionList({
      pageNum: jobsPagination.value.pageNum,
      pageSize: jobsPagination.value.pageSize
    })
    jobsList.value = userInfo.rows || []
    jobsPagination.value.total = userInfo.total || 0
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('获取岗位列表失败')
  }
}

const getUserListAll = async () => {
  try {
    const userInfo = await getUserList({
      pageNum: usersPagination.value.pageNum,
      pageSize: usersPagination.value.pageSize
    })
    usersList.value = userInfo.rows || []
    usersPagination.value.total = userInfo.total || 0
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

const getCustomersListAll = async () => {
  try {
    const userInfo = await cusomerList({
      pageNum: customersPagination.value.pageNum,
      pageSize: customersPagination.value.pageSize
    })
    customersList.value = userInfo.rows || []
    customersPagination.value.total = userInfo.total || 0
  } catch (error) {
    console.error('获取客户列表失败:', error)
    ElMessage.error('获取客户列表失败')
  }
}

// 客户转化（管理员）
const getCustomerConversion = async () => {
  try {
    const res = await customerConversion()
    if (res.data) {
      customerChartOption.value.xAxis.data = res.data.xaxis || []
      customerChartOption.value.series[0].data = res.data.yaxis || []
    }
  } catch (error) {
    console.error('获取客户转化数据失败:', error)
    ElMessage.error('获取客户转化数据失败')
  }
}

// 分享统计（管理员）
const getShareStatistic = async () => {
  try {
    const res = await shareStatistic()
    if (res.data) {
      shareChartOption.value.xAxis.data = res.data.xaxis || []
      shareChartOption.value.series[0].data = res.data.yaxis || []
    }
  } catch (error) {
    console.error('获取分享统计数据失败:', error)
    ElMessage.error('获取分享统计数据失败')
  }
}

// 业务员排行
const getSalesmanRanking = async () => {
  try {
    const res = await salesmanRanking()
    topUsers.value = res.data || []
  } catch (error) {
    console.error('获取业务员排行失败:', error)
    ElMessage.error('获取业务员排行失败')
  }
}

const tabChange = (pageName) => {
  if(pageName == 'statistics'){
    getCustomerConversion()
    getShareStatistic()
    getSalesmanRanking()
  }
}

// 分页事件处理
const handleJobsPageChange = (page) => {
  jobsPagination.value.pageNum = page
  getJobListAll()
}

// 分页事件处理
const handleIndexsPageChange = (page) => {
  indexsPagination.value.pageNum = page
  getIndexListAll()
}

const handleUsersPageChange = (page) => {
  usersPagination.value.pageNum = page
  getUserListAll()
}

const handleCustomersPageChange = (page) => {
  customersPagination.value.pageNum = page
  getCustomersListAll()
}

const handleIndexsSizeChange = (size) => {
  indexsPagination.value.pageSize = size
  indexsPagination.value.pageNum = 1
  getIndexListAll()
}
const handleJobsSizeChange = (size) => {
  jobsPagination.value.pageSize = size
  jobsPagination.value.pageNum = 1
  getJobListAll()
}

const handleUsersSizeChange = (size) => {
  usersPagination.value.pageSize = size
  usersPagination.value.pageNum = 1
  getUserListAll()
}

const handleCustomersSizeChange = (size) => {
  customersPagination.value.pageSize = size
  customersPagination.value.pageNum = 1
  getCustomersListAll()
}

const getTodayAll = async () => {
    const info = await todayNewAdditions()
    todayNewCount.value = info.data
}

// 业务员排行 - 这里需要根据实际API调整
const topUsers = ref([])

// 初始化数据
onMounted(() => {
  // 加载分页数据
  getJobListAll()
  getUserListAll()
  getCustomersListAll()
  getTodayAll()
  getIndexListAll()
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    contacted: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待联系',
    contacted: '已联系',
    rejected: '已拒绝'
  }
  return statusMap[status] || '未知'
}

// 岗位管理
const showAddJobDialog = () => {
  isEditJob.value = false
  jobForm.value = {
    title: '',
    company: '',
    location: '',
    salary: '',
    experience: '',
    requirements: [''],
    benefits: [],
    education: '',
    description: '',
    images: [],
    videos: [],
    files: []
  }
  jobDialogVisible.value = true
}

// 网站管理
const showAddIndexDialog = () => {
  isEditIndex.value = false
  indexForm.value = {
    "bannerUrl": [],
    "bannerUrlList": [],
    "createBy": "",
    "createTime": "",
    "firstUrl": [],
    "params": {},
    "remark": "",
    "searchUrl": [],
    "status": "",
    "updateBy": "",
    "updateTime": "",
    "wwwName": ""
  }
  indexDialogVisible.value = true
}

const editJob = (job) => {
  isEditJob.value = true
  jobForm.value = { 
    ...job,
    requirements: job.requirements && job.requirements.length > 0
      ? job.requirementList
      : [''],
    benefits: job.benefits && job.benefits.length > 0
      ? job.benefitList
      : [],
    images: job.images && job.images.length > 0
      ? JSON.parse(job.images)
      : [],
    videos: job.videos && job.videos.length > 0
      ? JSON.parse(job.videos)
      : [],
    files: job.files && job.files.length > 0
      ? JSON.parse(job.files)
      : []
  }
  jobDialogVisible.value = true
}

const editIndex = (job) => {
  isEditIndex.value = true
  indexForm.value = {
    ...job,
//    bannerUrl: job.bannerUrlList && job.bannerUrlList.length > 0
//      ? job.bannerUrlList
//      : [],
    bannerUrl: job.bannerUrl && job.bannerUrl.length > 0
      ? JSON.parse(job.bannerUrl)
      : [],
    searchUrl: job.searchUrl && job.searchUrl.length > 0
      ? JSON.parse(job.searchUrl)
      : [],
    firstUrl: job.firstUrl && job.firstUrl.length > 0
      ? JSON.parse(job.firstUrl)
      : [],
  }
  indexDialogVisible.value = true
}

// 添加任职要求
const addRequirement = () => {
  jobForm.value.requirements.push('')
}

// 删除任职要求
const removeRequirement = (index) => {
  jobForm.value.requirements.splice(index, 1)
}

// 添加福利待遇
const addBenefit = () => {
  jobForm.value.benefits.push('')
}

// 删除福利待遇
const removeBenefit = (index) => {
  jobForm.value.benefits.splice(index, 1)
}

const saveJob = async () => {
  try {
    await jobFormRef.value.validate()
    const newObj = deepClone(jobForm.value)
    // 过滤掉空的任职要求
    const filteredRequirements = jobForm.value.requirements.filter(req => req && req.trim() !== '')
    jobForm.value.requirements = filteredRequirements
    
    // 过滤掉空的福利待遇
    const filteredBenefits = jobForm.value.benefits.filter(benefit => benefit && benefit.trim() !== '')
    jobForm.value.benefits = filteredBenefits

    if(newObj.images && newObj.images.length>0){
      newObj.images = JSON.stringify(newObj.images)
    }else{
      newObj.images = ""
    }
    if(newObj.files && newObj.files.length>0){
      newObj.files = JSON.stringify(newObj.files)
    }else{
      newObj.files = ""
    }
    if(newObj.videos && newObj.videos.length>0){
      newObj.videos = JSON.stringify(newObj.videos)
    }else{
      newObj.videos = ""
    }
    
    if (isEditJob.value) {
      // 编辑岗位
//      const index = jobsStore.jobs.findIndex(j => j.id === jobForm.value.id)
//      if (index !== -1) {
//        jobsStore.jobs[index] = { ...jobForm.value }
//      }
      const res = await positionUpdate({ ...newObj })
      ElMessage.success('岗位更新成功')
    } else {
      // 添加岗位
      const newJob = {
        ...newObj,
//        id: Date.now(),
//        publishTime: new Date().toLocaleDateString(),
        status: 'inactive'
      }
//      jobsStore.jobs.push(newJob)
      const res = await positionAdd(newJob)
      ElMessage.success('岗位添加成功')
    }
    jobDialogVisible.value = false
    // 重新加载当前页数据
    getJobListAll()
  } catch (error) {
    ElMessage.error('请完善岗位信息')
  }
}

const saveIndex = async () => {
  try {
    await indexFormRef.value.validate()
    const newObj = deepClone(indexForm.value)

    if(newObj.bannerUrl && newObj.bannerUrl.length>0){
      newObj.bannerUrl = JSON.stringify(newObj.bannerUrl)
    }else{
      newObj.bannerUrl = ""
    }
    if(newObj.firstUrl && newObj.firstUrl.length>0){
      newObj.firstUrl =  JSON.stringify(newObj.firstUrl)
    }else{
      newObj.firstUrl = ""
    }
    if(newObj.searchUrl && newObj.searchUrl.length>0){
      newObj.searchUrl = JSON.stringify(newObj.searchUrl)
    }else{
      newObj.searchUrl = ""
    }

    if (isEditIndex.value) {
      const res = await wwwinfoUpdate({ ...newObj })
      ElMessage.success('网站更新成功')
    } else {
      // 添加岗位
      const newJob = {
        ...newObj,
        status: 'inactive'
      }
      const res = await wwwinfoAdd(newJob)
      ElMessage.success('网站添加成功')
    }
    indexDialogVisible.value = false
    // 重新加载当前页数据
    getIndexListAll()
  } catch (error) {
    ElMessage.error('请完善网站信息')
  }
}

const toggleJobStatus = async (job) => {
  job.status = job.status === 'active' ? 'inactive' : 'active'
  const res = await positionUpdateStatus( job )
  ElMessage.success(`岗位已${job.status === 'active' ? '上线' : '下线'}`)
  getJobListAll()
}

const toggleIndexStatus = async (job) => {
  job.status = job.status === 'active' ? 'inactive' : 'active'
  const res = await wwwinfoUpdateStatus( job )
  ElMessage.success(`网站已${job.status === 'active' ? '上线' : '下线'}`)
  getIndexListAll()
}

const deleteIndex = async(job) => {
  ElMessageBox.confirm('确定要删除这个网站吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    const res = await wwwinfoDel( job.id )
//    const index = jobsStore.jobs.findIndex(j => j.id === job.id)
//    if (index !== -1) {
//      jobsStore.jobs.splice(index, 1)
    ElMessage.success('网站删除成功')
    getIndexListAll()
//    }
  })
}

const deleteJob = async(job) => {
  ElMessageBox.confirm('确定要删除这个岗位吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    const res = await positionDel( job.positionId )
//    const index = jobsStore.jobs.findIndex(j => j.id === job.id)
//    if (index !== -1) {
//      jobsStore.jobs.splice(index, 1)
    ElMessage.success('岗位删除成功')
    getJobListAll()
//    }
  })
}

// 批量删除网站
const batchDeleteIndexs = async () => {
  if (selectedIndexs.value.length === 0) {
    ElMessage.warning('请选择要删除的网站')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedIndexs.value.length} 个网站吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    try {
      const ids = selectedIndexs.value.map(job => job.id)
      await batchDeleteWwwinfo(ids)
      ElMessage.success('批量删除成功')
      selectedIndexs.value = []
      getIndexListAll()
    } catch (error) {
      ElMessage.error('批量删除失败')
    }
  })
}

// 批量删除岗位
const batchDeleteJobs = async () => {
  if (selectedJobs.value.length === 0) {
    ElMessage.warning('请选择要删除的岗位')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedJobs.value.length} 个岗位吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    try {
      const positionIds = selectedJobs.value.map(job => job.positionId)
      await batchDeletePositions(positionIds)
      ElMessage.success('批量删除成功')
      selectedJobs.value = []
      getJobListAll()
    } catch (error) {
      ElMessage.error('批量删除失败')
    }
  })
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedJobs.value = selection
}

const handleSelectionIndex = (selection) => {
  selectedIndexs.value = selection
}


// 文件上传相关方法

const handleImagesFirst = (images) => {
  indexForm.value.firstUrl = images
}
const handleImagesBanner = (images) => {
  indexForm.value.bannerUrl = images
}
const handleImagesSearch = (images) => {
  indexForm.value.searchUrl = images
}
const handleImagesChange = (images) => {
  jobForm.value.images = images
}

const handleVideosChange = (videos) => {
  jobForm.value.videos = videos
}

const handleFilesChange = (files) => {
  jobForm.value.files = files
}

// 用户管理
const showAddUserDialog = () => {
  isEditUser.value = false
  userForm.value = {
    username: '',
    name: '',
    role: '',
    phone: '',
    wechat: '',
    email: ''
  }
  userDialogVisible.value = true
}

const editUser = (user) => {
  isEditUser.value = true
  userForm.value = { ...user }
  userDialogVisible.value = true
}

const saveUser = async () => {
  try {
    await userFormRef.value.validate()
    if(isEditUser.value){
      await userPut(userForm.value)
    }else{
      await userPost(userForm.value)
    }
    ElMessage.success(isEditUser.value ? '用户更新成功' : '用户添加成功')
    userDialogVisible.value = false
    // 重新加载当前页数据
    getUserListAll()
  } catch (error) {
    ElMessage.error('请完善用户信息')
  }
}

const deleteUser = (user) => {
  ElMessageBox.confirm('确定要删除这个用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('用户删除成功')
  })
}

// 客户管理
const viewCustomer = (customer) => {
  ElMessageBox.alert(
    `客户详细信息：\n姓名：${customer.customerName}\n手机：${customer.phone}\n微信：${customer.wechat}\n邮箱：${customer.email}\n工作经验：${customer.experience}\n期望薪资：${customer.expectedSalary}`,
    '客户信息',
    {
      confirmButtonText: '确定'
    }
  )
}

const updateCustomerStatus = async (customer, status) => {
  try {
    // 这里应该调用API更新客户状态
     await cusomerUpdate(customer.customerId, { status })
//    customer.status = status
    ElMessage.success('状态更新成功')
    // 重新加载当前页数据
    getCustomersListAll()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

const exportAllCustomers = () => {
  ElMessage.success('所有客户数据导出成功')
}

// 退出登录
const logout = () => {
  userStore.logout()
  router.push('/')
  ElMessage.success('已退出登录')
}
</script>

<style scoped>
.admin-panel {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.header .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-link {
  color: white;
  text-decoration: none;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.nav {
  display: flex;
  align-items: center;
  gap: 20px;
}

.nav-item {
  color: white;
  text-decoration: none;
  padding: 8px 16px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.nav-item:hover,
.nav-item.active {
  background-color: rgba(255,255,255,0.2);
}

/* 主要内容 */
.main-content {
  padding: 40px 0;
}

/* 统计概览 */
.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  background: #667eea;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.stat-content h3 {
  margin: 0 0 5px 0;
  color: #666;
  font-size: 14px;
}

.stat-content .stat-number {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

/* 管理标签页 */
.admin-tabs {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.tab-content {
  padding: 20px 0;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.content-header h3 {
  margin: 0;
  color: #333;
}

/* 统计图表 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.chart-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.chart-card h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.chart-container {
  background: white;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
  background: white;
  border-radius: 4px;
}

.ranking-number {
  width: 30px;
  height: 30px;
  background: #667eea;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.ranking-name {
  flex: 1;
  font-weight: bold;
}

.ranking-count {
  color: #666;
  font-size: 14px;
}

/* 任职要求样式 */
.requirement-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.requirement-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.requirement-input {
  flex: 1;
}

.remove-btn {
  flex-shrink: 0;
}

.add-btn {
  align-self: flex-start;
  margin-top: 5px;
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  text-align: center;
}

/* 批量操作样式 */
.batch-actions {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .header .container {
    flex-direction: column;
    gap: 15px;
  }
  
  .nav {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .stats-overview {
    grid-template-columns: 1fr;
  }
  
  .content-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .requirement-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .remove-btn {
    align-self: flex-end;
  }
}
</style> 